package com.bdqn.t350.ch06.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.t350.ch06.bean.Role;
import com.bdqn.t350.ch06.exception.AddException;
import com.bdqn.t350.ch06.service.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    RoleService roleService;

    @ResponseBody
    @RequestMapping("/list")
    public Object list(Model model) {
        List<Role> roleList = roleService.selectList(null, new Role());
        //model.addAttribute("roleList", roleList);
        return roleList;
    }

    @RequestMapping("/listPage")
    public Object listPage(@RequestParam(name = "roleName", defaultValue = "") String roleName,
                           @RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                           Model model) {
        IPage<Role> page = new Page<>();
        page.setSize(5);
        page.setCurrent(pageIndex);
        Role role = new Role();
        role.setRoleName(roleName);
        List<Role> roleList = roleService.selectList(page, role);
        page.setRecords(roleList);
        model.addAttribute("roleName", roleName);
        model.addAttribute("page", page);
        return "role/list";
    }

    /**
     * 转向添加页面
     */
    @RequestMapping("/toadd")
    public String toadd(Model model) {
        return "role/add";
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public String save(Role role) {
        boolean bool = roleService.insert(role);
        if (bool) {
            return "redirect:/role/listPage";
        } else {
            throw new AddException(600, "添加数据异常");
        }
    }
}
